﻿/**
* settingsCtrl - AngularJS module for right sidebar.
*
*
* Credits
* =======
*
* Copyright 2015 LonghronShen <LonghronShen@Hotmail.com>
*/

(function () {
    "use strict";

    /**
     * Config
     */
    var moduleName = 'app';
    var DEFAULT_ID = '__default';

    /**
     * Module
     */
    var module;
    try {
        module = angular.module(moduleName);
    } catch (err) {
        // named module does not exist, so create one
        module = angular.module(moduleName, []);
    }

    module.controller('settingsCtrl', ['$scope', '$ngBootbox', 'dataService', function ($scope, $ngBootbox, dataService) {
        console.info("<settingsCtrl> Defining settingsCtrl...");

        var makeId = function (count) {
            var text = "";
            var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

            for (var i = 0; i < count; i++) {
                text += possible.charAt(Math.floor(Math.random() * possible.length));
            }

            return text;
        }

        var loadCredentials = function (skip, count) {
            dataService.getWebApiCredentials(skip, count).then(function (res) {
                res = res.data || { Response: { List: [] } };
                console.info("loadCredentials: getWebApiCredentials returned: ", res);
                $scope.gridApi.grid.options.totalItems = res.Response.List;
                $scope.credentialList = { data: res.Response.List };
                var currentPage = $scope.gridApi.grid.options.paginationCurrentPage;
                var totalPages = $scope.gridApi.pagination.getTotalPages();
                if (totalPages < currentPage) { $scope.gridApi.grid.options.paginationCurrentPage = 1; };
            }, function (rej) {
                $ngBootbox.alert(rej);
            });
        };

        $scope.appId = "";
        $scope.appSecrect = "";

        var paginationOptions = {
            pageNumber: 0,
            pageSize: 10,
            currentPage: 1,
            sort: null
        };

        $scope.generateRandomCredential = function () {
            $scope.appId = makeId(10);
            $scope.appSecrect = makeId(15);
        };

        $scope.addCredential = function () {
            if ($scope.appId.length !== 10 && $scope.appSecrect.length !== 10) {
                $ngBootbox.alert("AppId或AppSecrect非法。");
                return;
            }
            dataService.addWebApiCredentials($scope.appId, $scope.appSecrect).then(function (res) {
                $scope.refresh();
            }, function (rej) {
                $ngBootbox.alert(rej);
            });
        };

        $scope.deleteCredential = function (id) {
            dataService.removeWebApiCredential(id).then(function (res) {
                $scope.refresh();
            }, function (rej) {
                $ngBootbox.alert(rej);
            });
        };

        $scope.refresh = function () {
            var newPage = 0;
            var pageSize = paginationOptions.pageSize;
            paginationOptions.pageNumber = newPage * pageSize - pageSize;
            paginationOptions.currentPage = newPage;
            loadCredentials(parseInt(paginationOptions.pageNumber), paginationOptions.pageSize);
        };

        var _credentialList = $scope.credentialList = {
            data: [],
            enableSorting: false,
            paginationPageSizes: [10, 20, 30],
            useExternalPagination: true,
            useExternalSorting: true,
            enableColumnResizing: true,
            columnDefs: [
                { displayName: "序号", field: 'Id', enableColumnMenu: false, },
                { displayName: "App Id", field: 'AppKey', enableColumnMenu: false },
                { displayName: "App Secrect", field: 'AppSecrect', enableColumnMenu: false },
                {
                    displayName: "操作",
                    field: '操作',
                    cellFilter: 'checkmark',
                    cellTemplate: '<a class="primary fa fa-trash-o text-danger" title="删除" ng-click="grid.appScope.deleteCredential(row.entity.Id)"></a>', enableColumnMenu: false
                }
            ],
            onRegisterApi: function (gridApi) {
                $scope.gridApi = gridApi;
                gridApi.pagination.on.paginationChanged($scope, function (newPage, pageSize) {
                    paginationOptions.pageNumber = newPage * pageSize - pageSize;
                    paginationOptions.pageSize = pageSize;
                    paginationOptions.currentPage = newPage;
                    loadCredentials(parseInt(paginationOptions.pageNumber), paginationOptions.pageSize);
                });
            }
        };

        loadCredentials(paginationOptions.pageNumber, paginationOptions.pageSize);
    }]);
})();